var createError = require("http-errors");

var express = require("express");

var path = require("path");

var app = express();

// 接口文档生成工具集成
const swaggerUi = require("swagger-ui-express");
const swaggerDocument = require("./swagger.json");
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));

// 解析cookie
var cookieParser = require("cookie-parser");

// 日志
var logger = require("morgan");

let cors = require("cors");

app.use(cors());
// 日志中间
app.use(logger("dev"));

// 解析 json请求体 和 x-www-form-urlencoded 请求体
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 解析cookie
app.use(cookieParser());

// 指定静态资源的路径 为当前文件夹下的 public文件夹
app.use(express.static(path.join(__dirname, "public")));

// 插入测试数据
let initData = require("./initData/initData");
initData();

// 解析jwt
var { expressjwt } = require("express-jwt");
app.use(
  expressjwt({
    secret: "testaaaa",
    algorithms: ["HS256"],
  }).unless({
    path: [
      "/doc",
      // token 验证 排除了 注册 请求
      {
        url: "/api/front/users",
        methods: ["POST"],
      },
      {
        url: "/api/front/banners",
        methods: ["GET"],
      },
      {
        url: "/api/front/users/login",
        methods: ["POST"],
      },
      {
        url: "/api/users",
        methods: ["POST"],
      },
      // "/api/users/login",
      // "/api/users/login",
      {
        url: "/api/users/login",
        methods: ["POST"],
      },
      {
        // 排除 /api/artilces 开头的get请求
        url: /^\/api\/articles/,
        methods: ["GET"],
      },
      {
        url: "/api/upload/img",
        methods: ["POST"],
      },

      {
        // 排除 /api/front/artilces 开头的get请求
        url: /^\/api\/front\/articles/,
        methods: ["GET"],
      },
      // "/api/articles/users/:uid", 这样的路由，必须使用正则匹配
      // /^\/api\/articles\/users\/\w+/,
      // {
      //   url: /^\/api\/articles\/\w+/,
      //   methods: ["GET"],
      // },
    ],
  })
);

// 启动socket服务器
var initSocketServer = require("./socketServer.js");
initSocketServer();

// 自定义的路由
var usersRouter = require("./routes/users");
var baseRouter = require("./routes/base");
var articlesRouter = require("./routes/articles");
var bannersRouter = require("./routes/banners");
var tongjiRouter = require("./routes/tongji");

var articlesFrontRouter = require("./routes/frontApi/articles");
var usersFrontRouter = require("./routes/frontApi/users");
var cartsFrontRouter = require("./routes/frontApi/carts");
var bannersFrontRouter = require("./routes/frontApi/banners");
var uploadRouter = require("./routes/upload.js");
app.use("/api/users", usersRouter);

// 用户 管理后台的接口
app.use("/api/articles", articlesRouter);
app.use("/api/banners", bannersRouter);
app.use("/api/tongji", tongjiRouter);

//前台 用户 浏览文章的接口
app.use("/api/front/articles", articlesFrontRouter);
app.use("/api/front/users", usersFrontRouter);
app.use("/api/front/carts", cartsFrontRouter);
app.use("/api/front/banners", bannersFrontRouter);

app.use("/api/base", baseRouter);
// 配置上传图片的接口路由
app.use("/api/upload", uploadRouter);

// ******
app.use(function (err, req, res, next) {
  if (err.name === "Unauthorized Error") {
    res.status(401).json({ code: 0, msg: "token过期，请重新登录" });
  } else {
    next(err);
  }
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);

  // 返回错误信息页面
  // res.render("error");
  res.json({
    code: 0,
    msg: err.message,
  });
});

module.exports = app;
